import React, { useEffect, FC } from 'react';
import { Form, Input, Modal, DatePicker, Switch } from 'antd';
import { FormValues } from '../data';
import moment from 'moment';
import { check } from 'prettier';

const layout = {
  labelCol: { span: 5 },
};

interface UserModalProps {
  record: string | undefined;
  visible: boolean;
  closeModalVisible: () => void;
  onFinish: (values: FormValues) => void;
}

const UserModal: FC<UserModalProps> = props => {
  const {
    record,
    closeModalVisible,
    visible,
    onFinish,
    confirmLoading,
  } = props;
  const recordObj = record ? JSON.parse(record) : '';

  const [form] = Form.useForm();

  // todo hooks 定义
  useEffect(() => {
    form.setFieldsValue({
      ...recordObj,
      create_time: moment(recordObj.create_time),
      update_time: moment(recordObj.update_time),
      status: Boolean(recordObj.status),
    });
  }, [visible]);

  // todo 点击ok提交数据
  const handleOk = () => {
    form.submit();
  };

  // todo 重置表单
  const onReset = () => {
    form.resetFields();
  };

  // todo 改变状态
  const onChange = (s: boolean) => {
    form.setFieldsValue({
      status: !s,
    });
  };

  // todo 点击取消
  const handleCancel = (e: Object) => {
    onReset();
    closeModalVisible();
  };

  // todo 失败
  const onFinishFailed = (values: Object) => {
    console.log('失败', values);
  };

  return (
    <Modal
      title={recordObj.id ? `编辑对象：${recordObj.name}` : '新增表单'}
      visible={visible}
      onOk={handleOk}
      confirmLoading={confirmLoading}
      okText='确认'
      cancelText='取消'
      onCancel={e => {
        onReset();
        handleCancel(e);
      }}
      forceRender>
      <Form
        {...layout}
        name='basic'
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        initialValues={{
          status: true, // 设置默认值
        }}>
        <Form.Item
          label='名称'
          name='name'
          shouldUpdate
          rules={[{ required: true, message: '请输入名称!' }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label='邮箱'
          name='email'
          shouldUpdate
          rules={[{ required: true, message: '请输入邮箱!' }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label='创建时间'
          name='create_time'
          rules={[{ required: true, message: '请输入创建时间!' }]}>
          <DatePicker showTime />
        </Form.Item>
        <Form.Item
          label='更新时间'
          name='update_time'
          rules={[{ required: true, message: '请输入更新时间!' }]}>
          <DatePicker showTime />
        </Form.Item>
        {/* 这里要注意 ，表单默认子属性值字段是 value，这里应该使用 valuePropName 进行修改成Switch的属性 -> checked */}
        <Form.Item label='是否启用' name='status' valuePropName='checked'>
          <Switch />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UserModal;
